package com.runen.wnhz.runen.ui.activity.major;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.ViewPager;
import android.text.TextPaint;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.runen.wnhz.runen.R;
import com.runen.wnhz.runen.bean.CourseVideoBean;
import com.runen.wnhz.runen.bean.LessonLidBean;
import com.runen.wnhz.runen.bean.WantLearnBean;
import com.runen.wnhz.runen.common.utils.ACacheUtlis;
import com.runen.wnhz.runen.common.utils.Base64Utils;
import com.runen.wnhz.runen.common.utils.Constants;
import com.runen.wnhz.runen.common.utils.DisplayUtil;
import com.runen.wnhz.runen.common.utils.ImageUtils;
import com.runen.wnhz.runen.common.utils.NetStateUtils;
import com.runen.wnhz.runen.common.utils.NetUtils;
import com.runen.wnhz.runen.common.utils.OkHttpUtils;
import com.runen.wnhz.runen.common.utils.StatusBarCompatUtils;
import com.runen.wnhz.runen.common.utils.ToastUtil;
import com.runen.wnhz.runen.data.entity.LessonIntroductionEntity;
import com.runen.wnhz.runen.di.component.ApplicationComponent;
import com.runen.wnhz.runen.presenter.Contart.HomeContart;
import com.runen.wnhz.runen.presenter.iPresenter.IHomeCourseDetailPresenter;
import com.runen.wnhz.runen.ui.activity.BaseActivity;
import com.runen.wnhz.runen.ui.activity.main.SubmitOrderActivity;
import com.runen.wnhz.runen.ui.adapter.puadapter.CourseVpAdapter;
import com.runen.wnhz.runen.ui.fragment.major.CatalogFragment;
import com.runen.wnhz.runen.ui.fragment.major.DiscussFragment;
import com.runen.wnhz.runen.ui.fragment.major.IntroduceFragment;
import com.runen.wnhz.runen.ui.fragment.major.TestFragment;
import com.runen.wnhz.runen.widget.TitleBuilder;

import org.simple.eventbus.Subscriber;

import java.io.IOException;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.jzvd.JZVideoPlayer;
import cn.jzvd.JZVideoPlayerStandard;
import io.rong.imkit.RongIM;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;

/**
 * 课程详情界面
 * Created by Administrator on 2018-04-12.
 */

public class CourseDetailsActivity extends BaseActivity<IHomeCourseDetailPresenter> implements HomeContart.TeachView {

    public static final String LID = "lid";
    @BindView(R.id.vp_course)
    ViewPager vpCourse;
    @BindView(R.id.course_tab)
    TabLayout tabCourse;
    @BindView(R.id.ll_bottom)
    LinearLayout llBottom;
    List<Fragment> fragments = new ArrayList<>();
    FragmentManager fm;
    //课程Id，从上界面传过来
    String lid;
    @BindView(R.id.videoView)
    JZVideoPlayerStandard videoView;
    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.videoLayout)
    RelativeLayout videoLayout;
    @BindView(R.id.text_wantLearn)
    TextView textWantLearn;
    @BindView(R.id.image_xin)
    ImageView imageXin;
    @BindView(R.id.liner_want_learn)
    LinearLayout linerWantLearn;
    @BindView(R.id.tv_add_lesson)
    TextView tvAddLesson;
    //视频地址
    private String videoUrl;
    private String token = null;

    private boolean hasCollected = false;
    private String lessonLid;
    private List<LessonIntroductionEntity.ListBean> listBeanList;
    private String id_str;
    private List<String> lidList;
    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    Bitmap bitmap = (Bitmap) msg.obj;
                    if (bitmap != null) {
                        videoView.thumbImageView.setImageBitmap(bitmap);
                    }
                    break;
            }
        }
    };

    @Override
    protected int getLayoutView() {
        return R.layout.course_details_activity_layout;
    }

    @Override
    protected void onTitleClickListen(TitleBuilder.TitleButton clicked) {

    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ButterKnife.bind(this);
        setListener();
    }

    private void setListener() {
        JZVideoPlayerStandard.SAVE_PROGRESS = false;
        videoView.backButton.setVisibility(View.GONE);
        videoView.batteryLevel.setVisibility(View.GONE);
        videoView.mRetryLayout.setVisibility(View.GONE);
    }

    @Subscriber
    public void onReceiveWantLearnEvent(String want_learn) {
        if ("1".equals(want_learn)) {
            hasCollected = true;
            imageXin.setImageResource(R.mipmap.have_want_learn_xin);
        } else {
            hasCollected = false;
            imageXin.setImageResource(R.mipmap.icon_want);
        }
    }

    @Override
    protected void initStart() {
        lid = getIntent().getStringExtra("lid");
        StatusBarCompatUtils.getInstance().TranslucentStatusBar(this, R.color.title_green);
        if (ACacheUtlis.getInstance().getReqeustUser(this) != null) {
            token = ACacheUtlis.getInstance().getReqeustUser(this).getToken();
        }
        fm = getSupportFragmentManager();
        //所有跳到课程详情界面的必须带上参数lid
        fragments.add(IntroduceFragment.newInstance(token, getIntent().getStringExtra("lid")));
        fragments.add(CatalogFragment.newInstance(getIntent().getStringExtra("lid")));
        fragments.add(DiscussFragment.newInstance(getIntent().getStringExtra("lid")));
        fragments.add(TestFragment.newInstance("2"));
        initViewPagerAdapter(fragments);
        lidList = new ArrayList<>();
        if (lid != null) {
            getCourseVideoUrl(lid);
        }
    }

    private void getCourseVideoUrl(String lid) {
        if (lid != null) {
            FormBody formBody = new FormBody.Builder().add("lid", lid).build();
            //构建一个网络请求，从指定网址上面请求数据
            Request.Builder requestBuilder = new Request.Builder()
                    .url(NetUtils.COURSE_VIDEO_URL)
                    .post(formBody);
            //创建Call对象
            Call newCall = OkHttpUtils.getOkHttpClient().newCall(requestBuilder.build());
            newCall.enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            ToastUtil.showToast("视频链接请求失败");
                        }
                    });
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    if (response.isSuccessful()) {
                        ResponseBody responseBody = response.body();
                        String json;
                        if (responseBody != null) {
                            json = responseBody.string();
                            final String finalJson = json;
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    jsonDataDeal(finalJson);
                                }
                            });
                        }
                    }
                }
            });
        }
    }

    @Override
    public void onBackPressed() {
        if (JZVideoPlayer.backPress()) {
            return;
        }
        super.onBackPressed();
    }

    @Override
    protected void onPause() {
        super.onPause();
        JZVideoPlayer.releaseAllVideos();
    }

    private void jsonDataDeal(String json) {
        if (json != null) {
            CourseVideoBean courseVideoBean = new Gson().fromJson(json, CourseVideoBean.class);
            String re = courseVideoBean.getRe();
            if ("1".equals(re)) {
                CourseVideoBean.DataBean data = courseVideoBean.getData();
                String url = Base64Utils.decode(data.getTv_url());
                videoUrl = url.substring(3, url.length() - 5);
                playVideo(videoUrl);
            } else if ("0".equals(re)) {
                ToastUtil.showToast(courseVideoBean.getInfo());
            }
        }
    }

    private void playVideo(final String videoUrl) {
        new Thread() {
            @Override
            public void run() {
                Bitmap bitmap = ImageUtils.createVideoThumbnail(videoUrl, MediaStore.Images.Thumbnails.MINI_KIND);
                Message message = Message.obtain();
                message.what = 0;
                message.obj = bitmap;
                handler.sendMessage(message);
            }
        }.start();
        videoView.setUp(videoUrl, JZVideoPlayerStandard.SCREEN_WINDOW_NORMAL, "");
        if (NetStateUtils.getNetWorkStatus(CourseDetailsActivity.this) == Constants.NETWORK_WIFI) {
            videoView.startVideo();
        } else if ((NetStateUtils.getNetWorkStatus(CourseDetailsActivity.this) != Constants.NETWORK_WIFI) && (preferences.getBoolean(Constants.SP_isAllowFluxWatch, false))) {
            videoView.startVideo();
            ToastUtil.showToast("当前正在使用流量播放视频哦");
        }
    }

    @Subscriber
    public void onReceiveLessonLidBean(LessonLidBean lessonLidBean) {
        if (lessonLidBean != null) {
            lessonLid = lessonLidBean.getLessonLid();
            listBeanList = lessonLidBean.getListBeanList();
        }
    }

    private void initViewPagerAdapter(List<Fragment> fragments) {
        List<String> mList = new ArrayList<>();
        mList.add("简介");
        mList.add("目录");
        mList.add("讨论");
        mList.add("考试");
        CourseVpAdapter vpAdapter = new CourseVpAdapter(getSupportFragmentManager(), fragments, mList);
        vpCourse.setAdapter(vpAdapter);
        vpCourse.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                if (position == 2 || position == 3) llBottom.setVisibility(View.GONE);
                else llBottom.setVisibility(View.VISIBLE);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        tabCourse.setupWithViewPager(vpCourse);
        //通过反射设置指示器长度
        setIndicator(this, tabCourse, 30, 30);
    }

    @OnClick({R.id.tv_add_lesson, R.id.iv_back, R.id.liner_want_learn, R.id.tv_consult})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_add_lesson:
                if (listBeanList != null && listBeanList.size() > 0) {
                    for (int i = 0; i < listBeanList.size(); i++) {
                        lidList.add(listBeanList.get(i).getLid());
                    }
                }
                if (lessonLid != null) {
                    Intent intent = new Intent(this, SubmitOrderActivity.class);
                    intent.putExtra("lessonLid", lessonLid);
                    String lidStr = lidList.toString();
                    intent.putExtra("id_str", lidStr.substring(1, lidStr.indexOf("]")));
                    startActivity(intent);
                }
                break;
            case R.id.iv_back:
                finish();
                break;
            case R.id.liner_want_learn:
                if (hasCollected) {
                    cancleWantCollection();
                } else {
                    saveWateLearn();
                }
                break;
            case R.id.tv_consult:
                if (!TextUtils.isEmpty(ACacheUtlis.getInstance().isLogin(this))) {
                    if (!ACacheUtlis.getInstance().isLogin(this).equals("true")) {
                        ToastUtil.showToast("您还没有登录，登陆之后才能咨询哦~");
                    } else {
                        if (RongIM.getInstance() != null) {
                            RongIM.getInstance().startPrivateChat(this, "18606532395", "186****2395");
                        }
                    }
                    break;
                } else {
                    ToastUtil.showToast("您还没有登录，登陆之后才能咨询哦~");
                }
                break;
        }
    }

    private void saveWateLearn() {
        if (token != null && lid != null) {
            FormBody formBody = new FormBody.Builder().add("token", token).add("type", "2").add("id", lid).build();
            //构建一个网络请求，从指定网址上面请求数据
            Request.Builder requestBuilder = new Request.Builder()
                    .url(NetUtils.USER_LESSON_COLLECTION)
                    .post(formBody);
            Call newCall = OkHttpUtils.getOkHttpClient().newCall(requestBuilder.build());
            newCall.enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            ToastUtil.showToast("数据请求失败");
                        }
                    });
                }

                @Override
                public void onResponse(Call call, final Response response) throws IOException {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                handleWantLearnData(response);
                            } catch (IOException e) {
                                e.printStackTrace();
                                ToastUtil.showToast("数据请求出现异常");
                            }
                        }
                    });
                }
            });

        }
    }

    private void cancleWantCollection() {
        if (token != null) {
            FormBody formBody = new FormBody.Builder().add("token", token).add("type", "1").add("id", lid).add("del", "1").build();
            //构建一个网络请求，从指定网址上面请求数据
            Request.Builder requestBuilder = new Request.Builder()
                    .url(NetUtils.USER_LESSON_COLLECTION)
                    .post(formBody);
            Call newCall = OkHttpUtils.getOkHttpClient().newCall(requestBuilder.build());
            newCall.enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            ToastUtil.showToast("数据请求失败");
                        }
                    });
                }

                @Override
                public void onResponse(Call call, final Response response) throws IOException {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                handleCancleWantLearnData(response);
                            } catch (IOException e) {
                                e.printStackTrace();
                                ToastUtil.showToast("数据请求出现异常");
                            }
                        }
                    });
                }
            });
        }
    }

    private void handleWantLearnData(Response response) throws IOException {
        if (response.isSuccessful()) {
            ResponseBody responseBody = response.body();
            if (responseBody != null) {
                String json = responseBody.string();
                WantLearnBean wantLearnBean = new Gson().fromJson(json, WantLearnBean.class);
                if (wantLearnBean != null) {
                    if ("1".equals(wantLearnBean.getRe())) {
                        ToastUtil.showToast(wantLearnBean.getInfo());
                        imageXin.setImageResource(R.mipmap.have_want_learn_xin);
                        hasCollected = true;
                    } else if ("0".equals(wantLearnBean.getRe())) {
                        ToastUtil.showToast(wantLearnBean.getInfo());
                    }
                }
            }
        }

    }

    private void handleCancleWantLearnData(Response response) throws IOException {
        if (response.isSuccessful()) {
            ResponseBody responseBody = response.body();
            if (responseBody != null) {
                String json = responseBody.string();
                WantLearnBean wantLearnBean = new Gson().fromJson(json, WantLearnBean.class);
                if (wantLearnBean != null) {
                    if ("1".equals(wantLearnBean.getRe())) {
                        ToastUtil.showToast(wantLearnBean.getInfo());
                        imageXin.setImageResource(R.mipmap.icon_want);
                        hasCollected = false;
                    } else if ("0".equals(wantLearnBean.getRe())) {
                        ToastUtil.showToast(wantLearnBean.getInfo());
                    }
                }
            }
        }

    }

    @Override
    public void initToolBar(TitleBuilder mTitleBuilder) {
        setToolBarVisible(View.GONE);
    }

    @Override
    public void setupAcitivtyComponent(ApplicationComponent appComponent) {

    }

    @Override
    public void initPresente() {
        //获取课程详情
//        mPresenter.getCourseDetail();
    }

    /**
     * 设置指示器的左右距离  相当于设置指示器长度
     *
     * @param context  context
     * @param tabs     tabLayout
     * @param leftDip  左间距
     * @param rightDip 右间距
     */
    public static void setIndicator(Context context, TabLayout tabs, int leftDip, int rightDip) {
        Class<?> tabLayout = tabs.getClass();
        Field tabStrip = null;
        try {
            tabStrip = tabLayout.getDeclaredField("mTabStrip");
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        }

        tabStrip.setAccessible(true);
        LinearLayout ll_tab = null;
        try {
            ll_tab = (LinearLayout) tabStrip.get(tabs);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }

        int left = (int) (DisplayUtil.getDisplayMetrics(context).density * leftDip);
        int right = (int) (DisplayUtil.getDisplayMetrics(context).density * rightDip);

        for (int i = 0; i < ll_tab.getChildCount(); i++) {
            View child = ll_tab.getChildAt(i);
            child.setPadding(0, 0, 0, 0);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.MATCH_PARENT, 1);
            params.leftMargin = left;
            params.rightMargin = right;
            child.setLayoutParams(params);
            child.invalidate();
        }
    }

    private void setBoldText(TextView boldText) {
        TextPaint tp = boldText.getPaint();
        tp.setFakeBoldText(true);
        boldText.invalidate();
    }

    private void setNormalText(TextView normalText) {
        TextPaint tp = normalText.getPaint();
        tp.setFakeBoldText(false);
        normalText.invalidate();

    }


    @Override
    public void showLoadding() {

    }

    @Override
    public void dimissLoding() {

    }

    @Override
    public void showErrorMessage(String msg) {

    }
}
